// ==UserScript==
// @namespace http://mrk.sed.pl/
// @include https://plus.google.com/*
// @exclude https://plus.google.com/*frame*
// @name Google+ Blocker
// @description Removes blocked users from all comments
// @version 0.6

// ==/UserScript==
// https://plus.google.com/116113476084412126173/about
// by mrk

function blocker_init() {
  var m = document.location.pathname.match(/\/u\/\d+\//)
  var url_prefix = m && m[0].slice(0,-1) || ''
  var at = OZ_initData[1][15];
  function set() {}
  set.prototype.difference_update = function(a) {for(var k in a) if(typeof a[k]=='boolean') delete this[k]}
  set.prototype.update = function(a) {for(var k in a) if(typeof a[k]=='boolean') this[k]=true}
  set.prototype.copy = function() {var r=new set;for(var k in this) if(typeof this[k]=='boolean') r[k]=true; return r}
  set.prototype.add = function(item) {this[item]=true;}
  set.prototype.items = function(){var out=[];for(var k in this) if(typeof this[k]=='boolean') out.push(k); return out;};
  set.prototype.persons = function(persons){out=[];for(var k in this) if(typeof this[k]=='boolean') out.push(persons[k]); return out;}
  function find_all(re, s){return (s.match(new RegExp(re,'g'))||[]).map(function(s){return s.match(new RegExp(re))})}
  function includes(s) {return find_all('include\\(([^\\)]+)\\)', s).map(function(i) {return i[1]})};
  function encode(payload) {var out=[];for(var k in payload) out.push(k + '=' + encodeURIComponent(payload[k])); return out.join('&')}

function hasClass(item, name) {
  return (item.getAttribute('class') || '').indexOf(name)>=0;
}
function addClass(item, name) {
  var cls = item.getAttribute('class') || '';
  if(!hasClass(item, name))
      item.setAttribute('class', cls + ' ' + name);
}
function toggleClass(item, name) {
  var cls = item.getAttribute('class') || '';
  cls = cls.split(' ')
  var has = cls.indexOf(name)>=0;
  cls = cls.filter(function(x){return x!=name})
  if(!has) cls.push(name);
  item.setAttribute('class', cls.join(' '));
}
function hide_comment(item) {
/*    setTimeout(function() {
        if(item.parentNode) item.parentNode.removeChild(item);
    },10);*/
    if(!hasClass(item, 'fixed')) {
      var author = item.querySelectorAll('a')[1];
      var name = author.innerHTML;
      addClass(item, 'hidden');
      addClass(item, 'fixed');
      var div=document.createElement('div');
      div.setAttribute('class', 'hidebar');
      var a = document.createElement('a');
      a.setAttribute('href', '#')
      a.appendChild(document.createTextNode('show'))
      a.addEventListener("click", function(ev) {
          toggleClass(item, 'hidden');
          ev.preventDefault();
      }, false)
      var descr = 'hidden, by ' + name + ' - ';
      div.appendChild(document.createTextNode(descr));
      div.appendChild(a);
      item.insertBefore(div, item.firstChild);
    }
}

function install_cleaner(parent, ids) {
//  var selector = ids.map(function(id) {return 'a[href="'+url_prefix + '/' + id+'"]';}).join(',');
  var selector = 'a.a-f-i-do[oid]';
  function clean(parent) {
    var nodes = parent.querySelectorAll(selector);
    for(var i=0; i<nodes.length; i++) {
      var p = nodes[i].parentNode.parentNode;
      if(p.getAttribute('class')=='a-f-i-W') {
        var post = p.parentNode.parentNode.parentNode.parentNode.parentNode
        var author_oid = post.querySelector('a[oid]').getAttribute('oid');
        var oid = nodes[i].getAttribute('oid')
        if(author_oid == oid) addClass(p, 'author-comment');
        if(ids.indexOf(oid)>=0)
          hide_comment(p);
      }
    }
  }
  clean(parent);
  parent.addEventListener("DOMNodeInserted", function(item) {
      clean(item.relatedNode);
  }, false)
}

  
  function send(url, cb, data) {
    var req = new XMLHttpRequest()
    req.open(data?'POST':'GET',url_prefix + url)
    if(data) {
        req.setRequestHeader('at', at);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        if(typeof data=='object') data=encode(data);
    }
    req.send(data);
    req.onreadystatechange = function() {
        if(this.readyState==4 && this.status==200) {
            cb(eval(this.responseText.slice(4)))
        }
    }
  }
  function add_members(cid, ids, cb) {
      if(!ids.length) return;
      var payload = {
          'c': '["'+cid+'"]',
          'm': '[['+ids.map(function(id){return '[[null,null,"'+id+'"],"",[]]' }).join(',')+']]',
          'at': at
      }
      send('/_/socialgraph/mutate/addmember/?rt=j', cb, payload);
  }
  var by_name={},by_id={},st={},persons={}
  send('/_/socialgraph/lookup/circles/?ct=2&m=1&tag=fg&rt=j', function(data) {
      var d=data[0][0];
      if(d[0]=='tsg.lac') {
          for(var i=0; i<d[1].length; i++) {
            var id=d[1][i][0][0];
            var name=d[1][i][1][0];
            var descr=d[1][i][1][2];
            var c=new set;
            c.name=name;c.id=id;
            c.includes=includes(descr||'')
            by_name[name]=by_id[id]=c;
          }
      }
      for(var i=0; i<d[2].length; i++) {
        var id=d[2][i][0][2];
        if(!id) continue;
        var name=d[2][i][2][0];
        var circles=d[2][i][3];
        persons[id] = name
        for(var j=0; j<circles.length; j++) {
          by_id[circles[j][2][0]].add(id);
        }
      }
      install_cleaner(document.body, by_id["15"].items())
  })

}

function blocker_set_stylesheet(config) {
    var styles = '.hidden .a-f-i-W-Lh-z {display:none}\n';
    styles += '.fixed .hidebar {text-align:right;display:none;color:#999;}\n';
    styles += '.fixed.hidden .hidebar {display:block;}\n';
    styles += '.author-comment {background-color:'+(config['blocker.author_comment_bgcolor'] || '#eee')+';}\n';
    if(config['blocker.collapse'] != 'true')
        styles += '.fixed.hidden {display:none;}\n';

        
    var style = document.getElementById('blocker_css')
    if(!style) {
        style = document.createElement('style');
        style.setAttribute('id', 'blocker_css')
        document.body.appendChild(style);
    }
    while(style.hasChildNodes()) style.removeChild(style.firstChild);
    style.appendChild(document.createTextNode(styles));
}

function init(config) {
    blocker_set_stylesheet(config);
    var script = document.createElement('script');
    script.appendChild(document.createTextNode(blocker_init.toString()));
    script.appendChild(document.createTextNode(blocker_set_stylesheet.toString()));
    script.appendChild(document.createTextNode('blocker_init();'))
    document.body.appendChild(script);
}

if(window.chrome && chrome.extension) {
    chrome.extension.sendRequest('get_config', function(config) {
        init(config)
    })
    chrome.extension.onRequest.addListener(function(req, sender, resp) {
        blocker_set_stylesheet(req);
    });
} else {
    init(window.localStorage || {})
}
